package com.automannn.seataSamples.order.service.impl;

import com.automannn.seataSamples.api.dto.AccountDTO;
import com.automannn.seataSamples.api.dto.OrderDTO;
import com.automannn.seataSamples.api.response.ObjectResponse;
import com.automannn.seataSamples.api.response.ResponseStatusEnum;
import com.automannn.seataSamples.api.service.AccountService;
import com.automannn.seataSamples.order.entity.OrderPO;
import com.automannn.seataSamples.order.mapper.OrderMapper;
import com.automannn.seataSamples.order.service.IOrderService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author automannn
 * @Date 2022/3/24
 */
@Service
public class IOrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implements IOrderService {

    @DubboReference(version = "1.0.0",group = "automannn")
    private AccountService accountService;

    @Override
    public ObjectResponse<OrderDTO> createOrder(OrderDTO orderDTO) {
        ObjectResponse<OrderDTO> response = new ObjectResponse<>();
        //第一步，扣减账户余额，确保账户余额充足
        AccountDTO accountDTO = new AccountDTO();

        accountDTO.setUserId(orderDTO.getUserId());
        accountDTO.setAmount(orderDTO.getOrderAmount());

        ObjectResponse objectResponse = accountService.decreaseAccount(accountDTO);

        //创建订单号
        orderDTO.setOrderNo(UUID.randomUUID().toString().replace("-",""));
        //订单持久化
        OrderPO orderPO = new OrderPO();
        BeanUtils.copyProperties(orderDTO,orderPO);

        orderPO.setCount(orderDTO.getOrderCount());
        orderPO.setAmount(orderDTO.getOrderAmount().doubleValue());

        try {
            baseMapper.createOrder(orderPO);
        }catch (Exception e){
            response.setStatus(ResponseStatusEnum.FAIL.getCode());
            response.setMessage(ResponseStatusEnum.FAIL.getMessage());
            return response;
        }

        //用户账户扣减成功，则判定业务失败
        if(objectResponse.getStatus()!=200){
            response.setStatus(ResponseStatusEnum.FAIL.getCode());
            response.setMessage(ResponseStatusEnum.FAIL.getMessage());
            return response;
        }

        response.setStatus(ResponseStatusEnum.SUCCESS.getCode());
        response.setMessage(ResponseStatusEnum.SUCCESS.getMessage());
        return response;

    }
}
